#include "csvreader.h"

CSVReader::CSVReader()
{
	
}

void CSVReader::setDelimiter(QChar delim)
{
	_delim = delim;
}

bool CSVReader::open(const QString &fileName)
{
	file.close();
	file.setFileName(fileName);
	if(!file.open(QIODevice::ReadOnly)){
		return false;
	}
	
	_data = QString::fromUtf8(file.readAll());	
	//qDebug() << "data="<<_data;
	file.close();
	_cursor = 0;
	
	if(next()){
		_columns = _currentData;
	}
	return true;
}

bool CSVReader::next()
{
	bool read = true;
	bool readed = false;
	QChar str_delim = '\"';
	QChar col_delim = _delim;
	QChar row_delim = '\n';
	QStringList columns;
	QString word;
	int i=0;
	while(1){
		if(_cursor>=_data.length()) break;
		QChar ch = _data[_cursor];
		if(ch=='\r'){
			i++;
			_cursor++;
			continue;
		}
		//qDebug() << Q_FUNC_INFO << "cursor=" << _cursor << "ch="<<ch << "read"<<read;
			
		if(ch==str_delim){
			//if(i!=0) read = !read;
			read = !readed;
			i++;
			_cursor++;
			continue;
		}
		
		if(ch==col_delim){
			//if(readed){
				columns << word;
				word="";
			//}
			read = true;
			readed = false;				
			_cursor++;
			i++;
			continue;
		}
		
		
		if((!read || !readed) && ch==row_delim){
			//qDebug() << Q_FUNC_INFO << read << readed;
			_cursor++;
			i++;
			if(!word.isEmpty()) columns << word;
			break;
		}

		if(read){
			word += ch;
			readed=true;
		}

		_cursor++;
		i++;
	}
	//qDebug() << Q_FUNC_INFO << "currentData" << _currentData;
	_currentData = columns;
	//if(_currentLine.isNull()) return false;
	//qDebug() << _currentData.count();
	if(_currentData.count()<2) return false;
	
	
	return true;
}

QStringList CSVReader::splitRow(const QString &data)
{
	bool read=true;
	bool isstring = false;
	QChar gran = '"';
	QString token="";
	QStringList tokens;
	for(int i=0;i<data.length();i++){		
		if(read && data[i]==gran){
			isstring = true;
			continue;
		}
		
		if(data[i]==_delim){
			tokens << token;
			token = "";
			read = false;
			continue;
		}
		if(data[i]==gran){
			read = !read;
			if(!read) tokens << token;
			token = "";
			continue;
		}
		if(read){
			token += data[i];
		}
		
	}	
	return tokens;
}

QStringList CSVReader::data()
{
	return _currentData;
}

QStringList CSVReader::columns()
{
	return _columns;
}

QString CSVReader::fileName()
{
	return file.fileName();
}


bool CSVReader::first()
{
	_cursor = 0;
	return next();
}

QString CSVReader::createInsert(int start,QString cube_name)
{
	QStringList names = columns();
	QStringList values = data();
	
	
	
	QStringList pairs;
	for(int i=start;i<names.count();i++){
		QString crdname = names.at(i);
		QString value = values.at(i);
		if(value.isEmpty()) continue;
		pairs << QString("\"%1\"=\"%2\"").arg(crdname).arg(value);
	}
	QString query = QString("insert into \"%1\" values %2").arg(cube_name).arg(pairs.join(","));
	return query;
}

